﻿/*========================== 
 * @author 郑金泉
 * @desc 类型相关实用工具
 * ========================= */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Obsidian.Utils
{
    public class TypeUtil
    {
        protected static Dictionary<string, Type> typeCache = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

        public static bool TryFindType(string typeName, out Type t)
        {
            lock (typeCache)
            {
                if (!typeCache.TryGetValue(typeName, out t))
                {
                    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        t = a.GetType(typeName);
                        if (t != null)
                        {
                            break;
                        }
                    }
                    typeCache[typeName] = t; // perhaps null
                }
            }
            return t != null;
        }


        public static bool TryFindType(string typeName, bool ignoreCase, out Type t)
        {
            return TryFindType(typeName, ignoreCase, AppDomain.CurrentDomain, out t);
        }

        public static bool TryFindType(string typeName, bool ignoreCase, AppDomain appDomain, out Type t)
        {
            lock (typeCache)
            {
                if (!typeCache.TryGetValue(typeName, out t))
                {
                    Assembly[] assemblies = appDomain.GetAssemblies();
                    foreach (Assembly a in assemblies)
                    {
                        t = a.GetType(typeName, false, ignoreCase);
                        if (t != null)
                        {
                            typeCache[typeName] = t; // perhaps null
                            break;
                        }
                    }
                }
            }
            return t != null;
        }

        public static bool IsDateTime(object val)
        {
            return val != null && val.GetType().ToString() == "System.DateTime";
        }

        public static string GetEnumName<T>(T val) where T : struct
        {
            string str = Enum.GetName(typeof(T), val);
            return str;
        }

    }
}
